﻿namespace RialternativeSample.Client.Views
{
    using System;
    using System.ServiceModel.DomainServices.Client.ApplicationServices;
    using System.Windows.Controls;
    using System.Windows.Input;
    using RialternativeSample;
    using RialternativeSample.Client.Models;
    using RialternativeSample.Views.Interfaces;

    /// <summary>
    /// Form that presents the login fields and handles the login process.
    /// </summary>
    public partial class LoginView : ChildWindow, ILoginView
    {
        /// <summary>
        /// Creates a new <see cref="LoginView"/> instance.
        /// </summary>
        public LoginView()
        {
            InitializeComponent();
        }

        public void ShowWindow()
        {
            base.Show();
        }

        public void CloseWindow()
        {
            base.Close();
        }

        public object Context
        {
            get
            {
                return this.DataContext;
            }
        }

        /// <summary>
        /// Handles <see cref="DataForm.AutoGeneratingField"/> to provide the PasswordAccessor.
        /// </summary>
        private void LoginForm_AutoGeneratingField(object sender, DataFormAutoGeneratingFieldEventArgs e)
        {
            //if (e.PropertyName == "Password")
            //{
            //    PasswordBox passwordBox = (PasswordBox)e.Field.Content;
            //    this.loginInfo.PasswordAccessor = () => passwordBox.Password;
            //}
        }

        /// <summary>
        /// Submits the <see cref="LoginOperation"/> to the server
        /// </summary>
        private void LoginButton_Click(object sender, EventArgs e)
        {
            // We need to force validation since we are not using the standard OK
            // button from the DataForm.  Without ensuring the form is valid, we
            // would get an exception invoking the operation if the entity is invalid.
            //if (this.loginForm.ValidateItem())
            //{
            //    this.loginInfo.CurrentLoginOperation = WebContext.Current.Authentication.Login(this.loginInfo.ToLoginParameters(), this.LoginOperation_Completed, null);
            //}
        }

        /// <summary>
        /// Completion handler for a <see cref="LoginOperation"/>. If operation succeeds,
        /// it closes the window. If it has an error, we show an <see cref="ErrorWindow"/>
        /// and mark the error as handled. If it was not canceled, but login failed, it must
        /// have been because credentials were incorrect so we add a validation error to
        /// to notify the user.
        /// </summary>
        private void LoginOperation_Completed(LoginOperation loginOperation)
        {
            if (loginOperation.LoginSuccess)
            {
                this.Close();
            }
            else if (loginOperation.HasError)
            {
                //ErrorWindow.CreateNew(loginOperation.Error);
                loginOperation.MarkErrorAsHandled();
            }
            else if (!loginOperation.IsCanceled)
            {
                //this.loginInfo.ValidationErrors.Add(new ValidationResult(ErrorResources.ErrorBadUserNameOrPassword, new string[] { "UserName", "Password" }));
            }
        }


        /// <summary>
        /// If a login operation is in progress and is cancellable, cancel it.
        /// Otherwise, close the window.
        /// </summary>
        private void CancelButton_Click(object sender, EventArgs e)
        {
            //if (this.loginInfo.CurrentLoginOperation != null && this.loginInfo.CurrentLoginOperation.CanCancel)
            //{
            //    this.loginInfo.CurrentLoginOperation.Cancel();
            //}
            //else
            //{
            //    this.Close();
            //}
        }

        /// <summary>
        /// Maps Esc to the cancel button and Enter to the OK button.
        /// </summary>
        private void LoginForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.CancelButton_Click(sender, e);
            }
            else if (e.Key == Key.Enter && this.loginButton.IsEnabled)
            {
                this.LoginButton_Click(sender, e);
            }
        }
    }
}
